var ns;
var searchBar, searchBarInput, searchBarBtn, searchBarClearBtn;
var app = new Vue({
    el: '#app',
    data: {
        form: {
            keywords: '',
            source: ''
        },
        list: []
    },
    methods: {
        do_search_by_key: function(keywords) {
            var that = this;
            that.form.keywords = keywords;
            that.do_search();
        },
        do_search: function() {
            var that = this;
            if (!that.form.keywords) {
                return;
            }
            that.add_in_list();
            var cansave = false;
            var title = '搜索结果';
            var name = '';
            api.sendEvent({
                name: 'do_search_complete',
                extra: {
                    keywords: that.form.keywords,
                    source: that.form.source
                }
            });
            setTimeout(function() {
                api.closeWin({});
            }, 100)
        },
        do_cancel: function() {
            api.closeWin();
        },
        do_remove_keywords: function() {
            var that = this;
            that.list = [];
            api.removePrefs({
                key: 'searchbar_keywords'
            });
        },
        add_in_list: function() {
            var that = this;
            if (that.form.keywords == '') {
                return;
            }
            if (that.list.length == 0) {
                that.list.push(that.form.keywords);
            }
            for (var i = 0; i < that.list.length; i++) {
                if (that.list[i] == that.form.keywords) {
                    break;
                }
                if (i == (that.list.length - 1)) {
                    that.list.push(that.form.keywords);
                }
            }
            api.setPrefs({
                key: 'searchbar_keywords',
                value: JSON.stringify(that.list)
            });
        },
        get_list: function() {
            var that = this;
            api.getPrefs({
                key: 'searchbar_keywords'
            }, function(ret, err) {
                if (ret && ret.value) {
                    that.list = eval('(' + ret.value + ')');
                }
            });
        }
    }
});
apiready = function() {
    api.parseTapmode();
    ns = window.Foresight.Util;
    app.form.source = api.pageParam.source || '';
    ns.init_search();
    app.get_list();
}

function doEnterSearchKey() {
    var keycode = '';
    if (window.event) { // IE8 及更早IE版本
        keycode = event.keyCode;
    } else if (event.which) { // IE9/Firefox/Chrome/Opera/Safari
        keycode = event.which;
    }
    if (keycode == 13) {
        var keywords = searchBarInput.value;
        if (keywords.length) {
            searchBarInput.blur();
            app.form.keywords = keywords;
            app.do_search();
        }
    }
}
